Uec3.ReceiveBrowserWindow = Ext.extend(Ext.app.Module, {
   id: 'receive_browser',
   type: 'common/receive_browser',
   permissionId:53,
   /**
    * Initialize this module.
    * This function is called at startup (page load/refresh).
    */
   init : function(initParams){
   		
   },
   browserReceiveDetails:function(id){
	   this.app.desktop.launchWindowByParam("receive_edit",{id:id,winId:id});	
   }, 
   
   deleteReceiveById : function(receiveId){   		
   	    var receive_browser_grid =  this.curWindow.get(0).get(1);
   	    var receive_browser_store = receive_browser_grid.getStore();
 		var currentCount = receive_browser_store.getCount();
 		Ext.MessageBox.confirm("提示","确定删除草稿?",function(btnId){
 			if(btnId=="yes"){
 				var myMask = new Ext.LoadMask(this.curWindow.el,{msg :'正在删除草稿中,请稍后.....'});
                myMask.show();
 				Ext.Ajax.request({
          			url:Uec3.App.Constants.homeUrl+"/receive/toReceive!deleteDraft.do",
          			params :{queryParam:receiveId},
          			method :"post",
          			timeout:180000,
          			callback :function(options,success,response){
                		myMask.hide();
         			},
          			success:function(response,options){
         				var resp = Ext.decode(response.responseText);
         				Ext.MessageBox.alert("提示",resp.msg);
             			if(resp.success){
             				if(currentCount == 1){	             			
               		   			receive_browser_grid.getBottomToolbar().movePrevious();
               				}else{
               		  			receive_browser_store.reload();
               				}	
             			}          							
          			},
          			failure:function(response,options){
             			Ext.MessageBox.alert("提示","发生异常，请稍候处理!");    
          			}
       			 });
 			}			
 		});	    
   },
	  
   
   getPanel:function(){
	   var module =this;
	   var ds_receive_status_select = new Ext.data.JsonStore({
           url:Uec3.App.Constants.homeUrl+"/dictionary/findByVarGroup.do?group=receive_status",
           root: "",
           autoLoad:true,
           fields:[{name:'varIndex',type:'int'},{name:'varName',type:'string'}]
      }); 
      
		var receive_browser_store = new Ext.data.JsonStore({
			url:Uec3.App.Constants.homeUrl+"/receive/toReceive!fillReceiveBrowser.do",				
			remoteSort :true,
		    root: "root",
            idProperty: "id",
            totalProperty: "totalProperty", 
            pruneModifiedRecords:true,
            fields:[
              'id','codeOfBuyer','codeOfSeller','statusName','amount','currentorName','creatorName',
              'submitterName','depositerName','memo','status','creatorId','currentorId',
              {name:'partnerName',mapping:'partnerNameByBuyer'},
              {name:'gmtSubmit',type:'date',dateFormat:'Y-m-d H:i:s'},
              {name:'gmtDepositer',type:'date',dateFormat:'Y-m-d H:i:s'},
              {name:'gmtCreate',type:'date',dateFormat:'Y-m-d H:i:s'},
              {name:'gmtAccept',type:'date',dateFormat:'Y-m-d H:i:s'}
            ]/*,
            listeners :{
               'beforeload':function(){
                    Ext.MessageBox.wait("正在加载数据...","提示");
               }
               'load':function(store,records,option){                             	
                    Ext.each(records,function(record,index,records){                   	
	    	            var recordId= record.data.id;	    	        
		                Ext.get('browserReceiveDetails_'+recordId).on('click',function(){
		             	    browserReceiveDetails(recordId);
		                });
		                if(record.data.status == 0 && record.data.currentorId == record.data.creatorId){
		                    Ext.get('deleteReceiveById_'+recordId).on('click',function(){
		             	       deleteReceiveById(recordId);
		                    });  
		                }		                           	
                    });
                }
         }*/
		});
			
		 var actionCol = {
					header : "操作",					
					sortable : false,
					dataIndex:'id',
					renderer : this.moduleActionRenderer([
					           {func : "browserReceiveDetails",desc : "打开"},
					           {func : "deleteReceiveById",
					            desc : "删除",
					            permission:module.permissionId,
					            isShow:function(value,metadata,record,rowIndex,store){
									if(record.data.status == 0 && record.data.currentorId == record.data.creatorId){
										return true;
									}
									return false;
								 }
					           }
		            ])
		};
		
		var receive_browser_grid = new Ext.grid.GridPanel({
			     //frame : false,
                 columnLines :true,
                 loadMask:{msg:'入库单列表加载中,请稍后....'},
                 //height:408,                   
                 enableHdMenu : false,
                 stripeRows: true,
                 //iconCls : 'icon-grid',
                 store:receive_browser_store,
                 width:'100%',
                 //forceLayout :true,
	   			 viewConfig:
	   			   {
	      		     //autoFill:true,
	      		     //forceFit:true,
	                 scrollOffset:25
	               },	   	   
	             autoScroll : true,
	             layout:"fit",
	            //autoExpandColumn:'memo',
	             defaults:{width:150},
		         columns:[
		            new Ext.grid.RowNumberer(),actionCol,	
		            {header:'单据号',dataIndex:'codeOfBuyer',width:135,sortable:true},
		            {header:'卖方',dataIndex:'partnerName',width:120},
		            {header:'卖方单据号',dataIndex:'codeOfSeller',width:125},
		            {header:'状态',dataIndex:'statusName',width:120},
		            {header:'金额(进价)',dataIndex:'amount',width:100},
		            {header:'当前处理人',dataIndex:'currentorName',width:125},
		            {header:'创建人',dataIndex:'creatorName',width:125},
		            {header:'创建时间',dataIndex:'gmtCreate',width:125,renderer:Ext.util.Format.dateRenderer('Y-m-d')},
		            {header:'提交人',dataIndex:'submitterName',width:125},
		            {header:'提交时间',dataIndex:'gmtSubmit',width:125,renderer:Ext.util.Format.dateRenderer('Y-m-d')},
		            {header:'审核人',dataIndex:'depositerName',width:125},
		            {header:'审核时间',dataIndex:'gmtDepositer',width:125,renderer:Ext.util.Format.dateRenderer('Y-m-d')},
		            {header:'入库时间',dataIndex:'gmtAccept',width:125,renderer:Ext.util.Format.dateRenderer('Y-m-d')},
		            {header:'备注',dataIndex:'memo',width:185}			           			            
		         ],
		        bbar:new Ext.PagingToolbar({		        	
		            pageSize:20,
	                store:receive_browser_store,
	                displayInfo: true,
	                displayMsg: '第 {0} - {1} 条  共 {2} 条',
                    emptyMsg: "没有记录 ",                    
                    listeners:{
                      /* beforechange:function(){
                    		 Ext.MessageBox.wait("正在加载数据...","提示");	                     
                       },
                       change:function(){
                           Ext.MessageBox.hide();
                       }*/
                    }
		         })
		         /*listeners:{
		             'afterrender':function(grid){
		             	 		             	
		             	 var records = this.getStore().getRange();		             	  
		             	 Ext.each(records,function(record,index,records){                   	
	    	                 var recordId= record.data.id;	    	        
		                     Ext.get('browserReceiveDetails_'+recordId).on('click',function(){
		             	         browserReceiveDetails(recordId);
		                     });
		                    if(record.data.status == 0){
		                       Ext.get('deleteReceiveById_'+recordId).on('click',function(){
		             	          deleteReceiveById(recordId);
		                       });  
		                    }		                           	
                        });
		                  
		             }
		         }*/
		});
		
		var view_panel = new Ext.FormPanel({			      
		      //applyTo:'receive_browser',
		      //autoScroll:true, 
		      border:true,
              //monitorResize: true,
              //frame:true,
              //layout:'border',
		      //width:'100%',
              //height:this.ownerCt.height,
		      //resizeEvent:'bodyresize',
		      items:[
		      	{ 		      	
		          height:60,
		          layout:'hbox',
		          border:false,
		          layoutConfig: 
		             {     
		               padding:'5',
					   align:'middle' 
                  },            
		          items:[			             
		             {
		               xtype:'label',
		               text:'浏览入库单',
		               style: {font:'bold 30px arial,serif'}
		              
		             },{
		             	xtype:'button',
		             	text: '切换到明细浏览方式',
		             	margins:'0 10',
		             	handler:function changeToReceiveItemBrowser(){															 
		  							 redirectUrl("receive_item_browser");
		                       } 
		             },{
		                xtype:'spacer',
                        flex:1 
		             },{
                        xtype:'numberfield',
                        name:'codeOfBuyer',
                        id:'codeOfBuyer'
                     },{
                        xtype:'button',
                        text:'查找单据号',                   
                        margins:'0 10',
                        handler:searchByCode
                     },{
                        xtype:'button',
                        text:'高级查找',
                        handler:function(){
                        	receive_browser_win.show();
                        }
                     },{
                        xtype:'spacer',
                        flex:1
                     },{
                        xtype:'button',
                        text: '新增采购进货',
                        handler:function(){      
                	     redirectUrl("receive_edit");
                        }
                    },{
                        xtype:'button',
                        text: '新增采购退货', 
                        margins:'0 10',
                        handler:function(){
                           redirectUrl("returned_edit");
                        }
                    }
		          ]
		      },receive_browser_grid
		    ]
		});
		
		var advanced_search_form = new Ext.form.FormPanel({
		         labelSeparator : "：",
		         frame:true,
		         border:false,
		         buttonAlign:'center',
		         labelWidth:70,
		         defaults:{anchor:'100%',width:160},
		         items:[
		            {
		              xtype:'textfield',
		              fieldLabel:'单据号',
		              name:'codeOfBuyer'
		            },{
		               xtype:'combo',
				       allowBlank : false,
					   name : 'status',
					   fieldLabel:'单据状态',
				       valueField:'varIndex',
                       displayField : 'varName',
  				       mode : 'remote',
				       hiddenName:'status',
				       store : ds_receive_status_select,
				       selectOnFocus : true,
				       forceSelection: true,
				       triggerAction : 'all',
				       loadingText : '加载中...',
				       editable:true,
				       emptyText : '请选择...'	 			     
		            },{
		               xtype:'textfield',
		               fieldLabel:'供货商',
		               name:'partnerName' 
		            },{
		               xtype:'datefield',
		               fieldLabel:'开始时间',
		               name:'gmtStart' ,
		               format:'Y-m-d'
		            },{
		               xtype:'datefield',
		               fieldLabel:'结束时间',
		               name:'gmtEnd',
		               format:'Y-m-d'
		            },{
		               xtype:'panel',
		               layout:'hbox',
		               border: false,
		               ctCls:'x-form-item',
		               items:[
		                 {
		                   xtype:'label',
		                   text:'进价(金额)：',
		                   margins:'0 0'
		                  // style:'font-size:15px'
		                   //ctCls:'x-form-item-label'
		                 },{
		                   xtype:'textfield',
		                   name:'minAmount',
		                   width:110,
		                   margins:'0 0 0 5'
		                 },{
		                    xtype:'label',
		                    text:'——'
		                 },{
		                    xtype:'textfield',
		                    name:'maxAmount', 
		                    width:110
		                 }
		              ]
		              
		            }
		         ],
		      buttons:[
		        { 
		          text:'查找',
				  handler:searchReceiveByCondition
		        },{
		     	  text:'关闭',
		     	  handler:function(){	
		     	    receive_browser_win.hide();
		     	  }
		        }
		      ]
			
		});
		
		var receive_browser_win = new Ext.Window({
			title:'高级查找',
		    layout:'fit',
	    	width:350,
	    	closeAction:'hide',
	    	height:260,
			resizable :true,
			shadow : true,
			modal :true,
	    	closable:true,
	    	//bodyStyle:'padding:5 5 5 5',
	    	animCollapse:true,
			items:[advanced_search_form],
			listeners:{
			  'show':function(){
			  	  var form =  receive_browser_win.get(0).getForm();
			  	  if(form.el){
			     	 form.el.dom.reset();
		    	  }else{
			      	form.reset();
		    	  } 
			  }
			}
	    });
	    
	    function searchByCode(){
	      var value=view_panel.findById('codeOfBuyer').getValue();		     
	      var queryParam=Ext.util.JSON.encode({codeOfBuyer:value});		      
		  loadReceive(queryParam);		      
	    }
		
		function searchReceiveByCondition(){
		   var queryParam =Ext.util.JSON.encode(advanced_search_form.getForm().getValues());
		   loadReceive(queryParam);
		   receive_browser_win.hide();
		}

		 function loadReceive(queryParam){
			 if(queryParam){
				 receive_browser_store.baseParams = {start:0,limit:20,queryParam:queryParam}; 
			 }else{
				 receive_browser_store.baseParams = {start:0,limit:20};
			 }
		    receive_browser_store.load({callback:function(records,options,success){
	              if(success){
	              	 Ext.MessageBox.hide();
	                 var total=records.length;
	                 if(!total){
	                    Ext.MessageBox.alert("提示","未找到相关记录");
	                 }
	              }else{
	                 Ext.MessageBox.alert("提示","数据加载异常");
	              }
		    }});
	    }
		 
		function redirectUrl(id,params){
		     var desktop =Uec3.App.getDesktop();   
		     desktop.launchWindowByParam(id,params); 	 		
		 }
		 
        return view_panel;
   },
	/**
	 * Create this modules window here.
	 */
   createWindow : function(){
      var desktop = this.app.getDesktop();
      var win = desktop.getWindow('receive_browser');
      if(!win){     	
         win = desktop.createWindow({
            id: 'receive_browser',
            title: '入库单浏览',
            width: 1000,
            height: 500,
            minWidth:785,
            minHeight:500,
            iconCls: 'acc-icon',
            shim: false,
            animCollapse: false,
            constrainHeader: true,
            maximizable: true,
            maximized:true,
            //autoScroll:true,
            taskbuttonTooltip: "入库单浏览",
            //monitorResize:true,
            //layout: "fit",          
            items:[this.getPanel()]
         }); 
      }
      win.get(0).get(1).getBottomToolbar().doRefresh();//刷新列表 
      win.get(0).get(1).setHeight(win.getHeight()-90);
      win.show(); 
      win.on('resize',function(win,width,height){
      	  win.get(0).get(1).setHeight(height-92);
      });
   }
});